import React, { useEffect, useRef, useState } from 'react'
import MonacoEditor from 'react-monaco-editor';
import request from '@/utils/request';
import { history } from 'umi';
import { Dropdown, Menu, Space, Button,message, Popconfirm } from 'antd';
import "./workEditor.less"
import { IButtonMenu, IDomEditor, IEditorConfig, IToolbarConfig, Boot } from '@wangeditor/editor'
import markdownModule from '@wangeditor/plugin-md'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import {useParams} from "umi"
type Props = {}


class MyButtonMenuC implements IButtonMenu {   // TS 语法
  // class MyButtonMenu {  
  title: string                     // JS 语法
  iconSvg: string
  tag: string
  constructor() {
    this.iconSvg = '<svg className="icon-wj" viewBox="0 0 1072 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3023" width="32" height="32"><path d="M491.9107146 202.62499973h209.1696427a88.39285674 88.39285674 0 0 1 88.39285675 88.39285757 32.1428573 32.1428573 0 1 0 64.28571459 0 152.67857136 152.67857136 0 0 0-152.67857134-152.67857135H491.9107146a32.1428573 32.1428573 0 1 0 0 64.28571378z m61.67410648 56.25000027L482.5491073 116.00000027a32.1428573 32.1428573 0 1 0-57.57589325 28.60714271l74.37053595 149.58482107a52.2321427 52.2321427 0 0 0 46.76785702 28.96875055H813.33928595A88.39285674 88.39285674 0 0 1 901.7321427 411.55357136v321.42857134a32.1428573 32.1428573 0 1 0 64.2857146 0V411.55357136A152.67857136 152.67857136 0 0 0 813.33928595 258.875h-259.75446487z m348.14732162 273.5357146V773.16071433a88.39285674 88.39285674 0 0 1-88.39285675 88.39285674H250.83928567A88.39285674 88.39285674 0 0 1 162.44642893 773.16071433V250.83928567A88.39285674 88.39285674 0 0 1 250.83928567 162.44642893h202.90178568a32.1428573 32.1428573 0 1 0 0-64.2857146H250.83928567A152.67857136 152.67857136 0 0 0 98.16071433 250.83928567v522.32142866A152.67857136 152.67857136 0 0 0 250.83928567 925.83928567h562.50000028a152.67857136 152.67857136 0 0 0 152.67857135-152.67857134v-240.74999973a32.1428573 32.1428573 0 1 0-64.2857146 0z" p-id="3024"></path></svg></svg>' // 可选
    this.tag = 'button'
    this.title = "打开文件"
  }
  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {   // TS 语法
    // getValue(editor) {                              // JS 语法
    return true
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(editor: IDomEditor): boolean {  // TS 语法
    // isActive(editor) {                    // JS 语法
    return false
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(editor: IDomEditor): boolean {   // TS 语法
    // isDisabled(editor) {                     // JS 语法
    return false
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, value: string | boolean) {
    // fileFlag = value
    if (typeof value === "string") {
      editor.insertText(value)
    }
    console.log(value, 'value')
    // console.log(fileFlag, 'editor');
  }
}

Boot.registerMenu({
  key: 'a3',
  factory() {
    return new MyButtonMenuC()
  }
})
const Editors = (props: Props) => {
const params:any = useParams()
    const menu = (
        <Menu
          items={[
            {
              key: '1',
              label: (
                <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
                  查看
                </a>
              ),
              disabled: true,
            },
            {
              key: '2',
              label: (
                <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
                  设置
                </a>
              ),
            },
            {
              key: '3',
              label: (
                <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
                  保存草稿
                </a>
              ),
            },
            {
              key: '4',
              label: (
                <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
                  删除
                </a>
              ),
              disabled: true,
            },
          ]}
        />
      );


      // 编辑器内容
      const [editor, setEditor] = useState<IDomEditor | null>(null)
  // const [html, setHtml] = useState('')
  Boot.registerModule(markdownModule)
  const tocBox=useRef(null)
  const [conect, setconect] = useState<IDomEditor|null>(null)
  const [low, setlow] = useState("")
  // 编辑器内容
  const [html, setHtml] = useState('')
  // console.log(html);

  // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    // toolbarKeys:["bold"],
    insertKeys: {
      index: 32,
      keys: "a3"
    }
  }  // TS 语法
  // console.log(editor?.getAllMenuKeys);
  // const toolbarConfig = { }                        // JS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {    // TS 语法
    // const editorConfig = {                         // JS 语法
    placeholder: '请输入内容...',
    onChange(e:any) {
      const  headers = e.getElemsByTypePrefix("header");
      (tocBox.current as unknown as HTMLDivElement).innerHTML=headers.map((header: any)=>{
        const text=(header.children[0] as any).text
        const {id,type}=header as any
        return `<li id="${id}" type="${type}">${text}</li>`
      }).join("")
    },
  }
   //点击toc滚动
   const handleTocClick=(e:any)=>{
    if(e.target.tagName==="LI"){
      editor?.scrollToElem(e.target.id);
    }
  }
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  const [titles,setTitles] = useState('')
  const [contents,setContents] = useState('')
  const [main,setMain] = useState({} as any)
useEffect(()=>{
  request.get(`http://111.67.198.176:8103/api/article/${params.id}`).then(res=>{
    setTitles(res.data.data.title)
    setContents(res.data.data.content)
    setMain(res.data.data)
  })
},[])


      const confirm :any= (e: React.MouseEvent<HTMLElement>) => {
        console.log(e);
        history.push("/pages/articlework/allarticle")
      };
      
      const cancel:any = (e: React.MouseEvent<HTMLElement>) => {
        console.log(e);
        message.error('Click on No');
      };


       //编辑or预览
  const [write, setwrite] = useState(false)
  const [writevalue, setwritevalue] = useState("编辑")
  //两栏观看
  const [twolan, settwolan] = useState(false)
  const [lanvalue, setlanvalue] = useState("两栏显示")
  //大纲
  const [outline, setoutline] = useState(false)
  const [outlinevalue, setoutlinevalue] = useState("大纲")


  // 上传
  const handleUpload = (e: any) => {
    const { files } = e.target;
    let formDate = new FormData()
    formDate.append('file', files[0])
    request.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('token')}`
    request({
      url: "/api/file/upload?unique=0",
      method: 'post',
      data: formDate,
    }).then(async (res1) => {
      message.success('上传成功');
    
    })
  }
  return (
    <div className='workEditor'>
        <header>
        <Popconfirm
                        title="确认关闭？如果有内容变更，请先保存。"
                        onConfirm={confirm}
                        onCancel={cancel}
                        okText="确认"
                        cancelText="取消"
                    >
        <Button className='workEditorbtn'>x</Button>
        </Popconfirm>
        <input type="text" value={titles} onChange={((e)=>{setTitles(e.target.value)})} />
        <Button type='primary' className='releasebtn'
        onClick={()=>{
          request.patch(`http://111.67.198.176:8103/api/article/${params.id}`,{
            category:main.category,
            content:contents,
            cover:main.cover,
            createAt:main.createAt,
            html:main.html,
            id:params.id,
            isCommentable: main.isCommentable,
            usPay:false,
            isRecommended:main.isRecommended,
            likes:main.likes,
            needPassword: main.needPassword,
            publishAt: main.publishAt,
            status:main.status,
            summary:main.summary,
            tags:main.tags,
            title:titles,
            toc:main.toc,
            totalAmount:main.totalAmount,
            updateAt: new Date().toString(),
            views:main.views
          }).then(res=>{
            console.log(titles,"111");
            message.success("发布成功")
          })
        }}
        >发布</Button>
        <Dropdown overlay={menu}>
          <a onClick={e => e.preventDefault()}>
                                <Space>
            <svg className="icon-more" fill='#1890ff' viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2161" width="32" height="32"><path d="M288 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2162"></path><path d="M512 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2163"></path><path d="M736 512m-64 0a64 64 0 1 0 128 0 64 64 0 1 0-128 0Z" p-id="2164"></path></svg>
            </Space>
            
          </a>
        </Dropdown>
      </header>
      <main>
        <div className='fwbmain' style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <div className='kheader'>
            <Toolbar
              editor={editor}
              defaultConfig={toolbarConfig}
              mode="default"
            />
            <p className='lan'>
              当前模式:<span onClick={() => {
                setwrite(!write)
                write ? setwritevalue("预览") : setwritevalue("编辑")
              }}>{writevalue}</span><span onClick={() => {
                settwolan(!twolan)
                twolan ? setlanvalue("退出两栏显示") : setlanvalue("两栏显示")
              }}>{lanvalue}</span><span onClick={() => {
                setoutline(!outline)
              }}>{outlinevalue}</span>
            </p>
          </div>

          <div className='writebox'>
            <Editor
              defaultConfig={editorConfig}
              value={contents}
              onCreated={setEditor}
              //@ts-ignore
              onChange={editor => setHtml(editor.getHtml())}
              mode="default"
              style={{ flex: "1", height: "100%", overflowY: 'auto', float: "left" }}
            />
            {
              twolan ? <></> : <div className='htmlinner' dangerouslySetInnerHTML={{ __html: html }} />
            }
            {
              outline ? <></> : <div className='lowbox'id="tocBox" ref={tocBox} onClick={(e)=>{
                handleTocClick(e)
              }}></div>
            }
          </div>
        </div>
      </main >
    </div>
  )
}

export default Editors